package net.tngou.action.api;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;

import javax.servlet.ServletException;

import org.apache.commons.lang.math.NumberUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.document.DoublePoint;
import org.apache.lucene.document.IntPoint;
import org.apache.lucene.document.LongPoint;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser.Operator;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.BooleanClause.Occur;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import net.tngou.action.BaseAction;
import net.tngou.lucene.Page;
import net.tngou.lucene.TngouDBHelp;
import net.tngou.pojo.Data_comp;
import net.tngou.util.DateUtil;
import net.tngou.util.ExcelUtils;
import net.tngou.util.MailUtil;
import net.tngou.util.StringUtil;

/**
 * 发生邮件
 * @author tngou@tngou.net
 *
 */
public class EmailApi  extends BaseAction {



	TngouDBHelp tngouDBHelp  = new TngouDBHelp();
	Analyzer analyzer = new SmartChineseAnalyzer();
	static LinkedHashMap<String, String> map = new LinkedHashMap<String, String>(){{  
	      put("企业名称","Name");  
	      put("登记状态","ShortStatus"); 
	      put("法定代表人","OperName");  
	      put("注册资本","RegistCap");  
	      put("成立日期","StartDate");  
	      put("核准日期","CheckDate");  
	      put("所属省份","Province");  
	      put("所属城市","City");  
	      put("所属区县","County");  
	      put("手机号码","Mtel");  
	      put("座机号码","Dtel");  
	      put("更多电话","Otel");  
	      put("邮箱","Email");  
	      put("统一社会信用代码","CreditCode");  
	      put("纳税人识别号","TaxNo");  
	      put("注册号","OrgNo");  
	      put("组织机构代码","OrgNo"); 
	      put("参保人数","InsuredCount"); 
	      put("企业类型","EconKind"); 
	      put("所属行业","Industry"); 
	      put("所属大类","SubIndustry"); 
	      put("曾用名","OriginalName"); 
	      put("英文名","EnglishName"); 
	      put("网址","WebSite");
	      put("企业地址","Address"); 
	      put("经营范围","Scope"); 
	      
	}};
	@Override
	public void execute() throws ServletException, IOException {
		String tableName="comp";
		String email= request.getParameter("email");
		if(StringUtil.isEmpty(email))
		{
			run_false("邮箱不能为空");
			return ;
		}
		String key= request.getParameter("keyword");//关键字
		String type= request.getParameter("type");//企业类型  不填是全部   0-个体 1-企业
		String isscope= request.getParameter("isscope");//是否通过经营范围匹配（默认不匹配，1-匹配）
		String ism= request.getParameter("ism");//有手机号（默认全部 1-有 0-没有）
		String isd= request.getParameter("isd");//有座机号（默认全部 1-有 0-没有）
		String scapi= request.getParameter("scapi");//注册资本范围最小值（默认为0）
		String ecapi= request.getParameter("ecapi");//注册资本范围最大值（默认为最大）
		String sdate= request.getParameter("sdate");//注册时间范围最小值（默认为0000-00-00）
		String edate= request.getParameter("edate");//注册时间范围最大值（默认为9999-99-99）
		String provincecode= request.getParameter("provincecode");//省份编码
		String citycode= request.getParameter("citycode");//城市编码
		String countycode= request.getParameter("countycode");//区(市)县
		String industrycode= request.getParameter("industrycode");//门类编码
		String subindustrycode= request.getParameter("subindustrycode");//大类编码
		BooleanQuery.Builder  builder=new BooleanQuery.Builder();
		
		if(StringUtil.isNotEmpty(key)) {
			String[] mysqlFields = { "Name", "OriginalName"};
			MultiFieldQueryParser qp=new MultiFieldQueryParser(mysqlFields,analyzer);
			qp.setDefaultOperator(Operator.OR);
			try {
				builder.add(qp.parse(key), Occur.MUST);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if("1".equals(isscope))
				builder.add(new TermQuery(new Term("Scope",key)), Occur.SHOULD);
			
		}
		if("1".equals(type)||"0".equals(type))
			builder.add(IntPoint.newExactQuery("Type", Integer.parseInt(type)), Occur.MUST);

		if("1".equals(ism)||"0".equals(ism))
			builder.add(IntPoint.newExactQuery("ism", Integer.parseInt(ism)), Occur.MUST);
		if("1".equals(isd)||"0".equals(isd))
			builder.add(IntPoint.newExactQuery("isd", Integer.parseInt(isd)), Occur.MUST);

		
		if(StringUtil.isNotEmpty(provincecode)) 
			builder.add(new TermQuery(new Term("ProvinceCode",provincecode)), Occur.MUST);
		if(StringUtil.isNotEmpty(citycode)) 
			builder.add(new TermQuery(new Term("CityCode",citycode)), Occur.MUST);
		if(StringUtil.isNotEmpty(countycode)) 
			builder.add(new TermQuery(new Term("CountyCode",countycode)), Occur.MUST);
		if(StringUtil.isNotEmpty(industrycode)) 
			builder.add(new TermQuery(new Term("IndustryCode",industrycode)), Occur.MUST);
		if(StringUtil.isNotEmpty(subindustrycode)) 
			builder.add(new TermQuery(new Term("SubIndustryCode",subindustrycode)), Occur.MUST);

			
		if(StringUtil.isNotEmpty(scapi)||StringUtil.isNotEmpty(ecapi))	
		{
			double s=0;
			double e=Double.MAX_VALUE;
			if(StringUtil.isNotEmpty(scapi)&&NumberUtils.isNumber(scapi))
				s=Double.parseDouble(scapi);
			if(StringUtil.isNotEmpty(ecapi)&&NumberUtils.isNumber(ecapi))
				e=Double.parseDouble(ecapi);
			builder.add(DoublePoint.newRangeQuery("Capi", s-1, e+1), Occur.MUST);
		}
		if(StringUtil.isNotEmpty(sdate)||StringUtil.isNotEmpty(edate))	
		{
			long s=0;
			long e=Long.MAX_VALUE;
			LocalDateTime sd = DateUtil.parse(sdate);
			LocalDateTime ed = DateUtil.parse(edate);
			if(sd!=null)s=DateUtil.toSqlDate(sd.toLocalDate().minusDays(1)).getTime();
			if(ed!=null)e=DateUtil.toSqlDate(ed.toLocalDate().plusDays(1)).getTime();
			builder.add(LongPoint.newRangeQuery("sdate", s, e), Occur.MUST);
		}
		
		Query query=builder.build();
		Page p = tngouDBHelp.select(tableName, ask.getPage(), ask.getSize(),   query);
		if(p.getTotal()==0)
			run_false("没有导出的企业！");
		// 创建线程池
		ExecutorService executor = Executors.newFixedThreadPool(1);
		CompletableFuture<String> future = CompletableFuture.supplyAsync(new Supplier<String>() {
			public String get() {
				//
				try {
					run(p,email);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return "执行完成!";
			}
		}, executor);
 
		//采用lambada的实现方式
		future.thenAccept(e -> System.out.println(e + " ok"));
		
		run_success("已经导出"+p.getList().size()+"家企业到"+email);
	}

	
	public static void run(Page page,String email) throws IOException {
		List<String> titles = new ArrayList<>(map.keySet());
		List<Map<String, Object>> values = new ArrayList<>();
		for (Map<String, Object> field : page.getList()) {
			
			Map<String, Object> e = new HashMap<>();
			Set<String> set = map.keySet();
			for (String k : set) {
				e.put(k,field.get(map.get(k)));
			}
			values.add(e );
		}
		String filepath="/home/"+page.hashCode()+".xlsx";
		
		System.err.println("开始写入"+values.size());
		long t = new Date().getTime();
		ExcelUtils.writeExcel(filepath, "名单", titles, values);
		
		File file= new File(filepath);
		boolean b = MailUtil.sendHtml(email, null,"内容见附件！",file);
		file.delete();
		System.err.println("完成写入"+(new Date().getTime()-t));
	}
	
	
}
